package com.youkeda.dewu.service.impl;

import com.youkeda.dewu.dao.ProductDAO;
import com.youkeda.dewu.dao.ProductDetailDAO;
import com.youkeda.dewu.dataobject.ProductDO;
import com.youkeda.dewu.model.Paging;
import com.youkeda.dewu.model.Product;
import com.youkeda.dewu.model.ProductDetail;
import com.youkeda.dewu.param.BasePageParam;
import com.youkeda.dewu.service.ProductService;
import com.youkeda.dewu.util.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 刘正星
 * @version 1.0.0
 * @ClassName ProductServiceImpl.java
 * @Description TODO
 * @createTime 2020年10月07日 19:30:00
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDAO productDAO;
    @Autowired
    private ProductDetailDAO productDetailDAO;

    @Override
    public int save(Product product) {
        if (StringUtils.isEmpty(product.getId())) {
            ProductDO productDO = new ProductDO(product);
            productDO.setId(UUIDUtils.getUUID());
            return productDAO.insert(productDO);
        }
        ProductDO productDO = new ProductDO(product);
        int update = productDAO.updateByPrimaryKey(productDO);
        return update;
    }

    @Override
    public Paging<Product> pageQueryProduct(BasePageParam param) {
        Paging<Product> result = new Paging<>();
        if (param == null) {
            return result;
        }
        if (param.getPagination() < 0) {
            param.setPagination(0);
        }
        if (param.getPageSize() < 0) {
            param.setPageSize(10);
        }
        //查询数据总数
        int count = productDAO.selectAllCounts();
        if (count < 0) {
            return result;
        }
        //组装返回数据
        result.setTotalCount(count);
        result.setPageSize(param.getPageSize());
        result.setPageNum(param.getPagination());
        int totalPage = (int) Math.ceil(count / (param.getPageSize() * 1.0));
        result.setTotalPage(totalPage);
        //实际返回的数据
        List<ProductDO> productDOS = productDAO.pageQuery(param);
        if (CollectionUtils.isEmpty(productDOS)) {
            return result;
        }
        List<Product> productList = productDOS.stream().map(productDO -> productDO.toModel()).collect(Collectors.toList());
        result.setData(productList);

        return result;
    }

    @Override
    public Product get(String productId) {
        if (StringUtils.isEmpty(productId)){
            return null;
        }
        Product product = productDAO.selectByPrimaryKey(productId).toModel();

        return product;
    }
}
